from django.db import models
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils.translation import gettext_lazy as _


class Course(models.Model):
    class COURSE_CATEGORY(models.TextChoices):
        COMPUTER = '计算机', _('计算机')
        SOFTWARE = '行业软件', _('行业软件')
        FOREIGN_LANGUAGE = '外语', _('外语')
        MATH = '数学', _('数学')
        LITERATURE = '文学', _('文学')
        ART = '艺术设计', _('艺术设计')
        SPORTS = '体育', _('体育')
        SCIENCE = '自然科学', _('自然科学')
        OTHER = '其他', _('其他')

    name = models.CharField(max_length=63, unique=True)
    about = models.CharField(max_length=255, blank=True, null=True)
    cover = models.URLField(blank=True, null=True)
    # 课程浏览量统计
    views = models.PositiveIntegerField(default=0)
    # 课程分类
    category = models.CharField(
        max_length=12, choices=COURSE_CATEGORY.choices, default=COURSE_CATEGORY.OTHER, null=False, blank=False)

    created_time = models.DateTimeField(auto_now_add=True)
    manager = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='managed_courses')

    class Meta:
        db_table = 'course'
        ordering = ['name']

    def __str__(self):
        return f'No.{self.id} {self.name}'  # pylint no-id error: ignore


class Introduction(models.Model):
    course = models.OneToOneField(
        Course, on_delete=models.CASCADE, related_name='introduction')
    content = models.TextField(null=False, blank=False)
    updated_time = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f'<Introduction for {self.course}>'

    class Meta:
        db_table = 'introduction'


# More about signals, See: https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html#onetoone

@receiver(post_save, sender=Course)
def create_introduction_by_default(sender, instance, created, **kwargs):
    if created:
        Introduction.objects.create(course=instance)
